package com.op.teachingliteapp.fragment.notif;

import java.util.ArrayList;
import java.util.List;

import android.widget.AbsListView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Fragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.op.teachingliteapp.R;
import com.op.teachingliteapp.bean.CourseNotifBean;
import com.op.teachingliteapp.common.Common;
import com.op.teachingliteapp.common.api.teachinglite.NotifUrl;
import com.op.teachingliteapp.database.dao.CourseNotifDao;
import com.op.teachingliteapp.fragment.NotifDetailFragment;
import com.op.teachingliteapp.util.ScreenSendUtils;
import com.op.teachingliteapp.util.StringUtils;
import com.op.teachingliteapp.util.asynctask.HttpPostTask;
import com.op.teachingliteapp.util.asynctask.OnTaskProcessListener;

/**
 * 
 * @author handsome
 *
 */

public class NotifFragment extends Fragment {

	private View root;
	private NotifDetailFragment notifDetailFragment = new NotifDetailFragment();
	private String getCourseUserId, getCourseId;
	public static NotifListAdapter mAdapter;
	public static ArrayList<NotifCellDataProvider> list_message = new ArrayList<NotifCellDataProvider>();

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_notif, container, false);
		this.root = view;

		
		SharedPreferences preferences = getActivity().getSharedPreferences(
				"TeachingLite", Context.MODE_PRIVATE);
		getCourseUserId = preferences.getString(Common.Prefs.USER_ID, "");
		getCourseId = preferences.getString(Common.Prefs.COURSE_ID, "");
		downLoadData();
		Log.i("NotifFragment", getCourseId + "");
		ListView list_message_view = (ListView) view
				.findViewById(R.id.message_listView);
		mAdapter = new NotifListAdapter(getActivity(), list_message);
		list_message_view.setAdapter(mAdapter);
		list_message_view.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				setBundle(position);// 传递通知到的详细参数

				getFragmentManager().beginTransaction().addToBackStack(null)
						.replace(R.id.main_show2, notifDetailFragment).commit();
			}
		});
       list_message_view.setOnScrollListener(new AbsListView.OnScrollListener() {
           @Override
           public void onScrollStateChanged(AbsListView view, int scrollState) {
               if (scrollState==SCROLL_STATE_IDLE) {
                   ScreenSendUtils.sendWithDely(root);
               }
           }

           @Override
           public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

           }
       });
   		return view;
	}

	/**
	 * 发送courseId从网上下拉通知json
	 */
	public void downLoadData() {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("courseId", getCourseId));
		HttpPostTask task = new HttpPostTask(getActivity(),
				NotifUrl.GET_COURSE_NOTIF_AND_OWNER_BY_COURSE_ID, params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
			}

			@Override
			public void completed(String result) {
				if (StringUtils.isEmptyOrStringNull(result)) {
					getDataFromDatabase();
				} else {
					Log.i("", "通知" + result);
					// 有网络登陆时
					analytical(result);
					getDataFromDatabase();
				}
				mAdapter.notifyDataSetChanged();
				ScreenSendUtils.sendWithDely(root);

			}

		});
		task.execute();// 执行结束，圈转完
		// ScreenSendUtils.send(root);
	}

	/**
	 * 从数据库获取数据 // 从数据库提取课程通知内容
	 */
	public void getDataFromDatabase() {
		CourseNotifDao courseNotifDao = new CourseNotifDao(getActivity(),
				getCourseUserId);
		List<CourseNotifBean> courseNotif = courseNotifDao
				.getNotifByCourseId(getCourseId);
		list_message.clear();
		// 获取讨论标题
		for (int i = 0; i < courseNotif.size(); i++) {
			String title = courseNotif.get(i).getTitle();
			String time = courseNotif.get(i).getCreateTime();
			String context = courseNotif.get(i).getContent();
			String name = courseNotif.get(i).getUserBean().getName();
			String image = courseNotif.get(i).getUserBean().getImageUrl();
			String courseNotifId = courseNotif.get(i).getId();
			String type = courseNotif.get(i).getUserBean().getType();
			list_message.add(new NotifCellDataProvider(image, name,type, title,
					context, time, courseNotifId));

		}

	}

	/**
	 * 解析json，并存入数据库
	 */
	public void analytical(String result) {
		Log.i("TAG", "cscacacccasca" + result);
		// 判断得到的数据是否为null
		if (!StringUtils.isEmptyOrStringNull(result)) {
			try {
				JSONObject jsonobjectresult = new JSONObject(result);
				String message = jsonobjectresult.getString("message");

				if (message.equals("Success")) {
					CourseNotifDao courseNotifDao = new CourseNotifDao(
							getActivity(), getCourseUserId);
					// 清空数据库
					courseNotifDao.empty();
					JSONObject resultMap = jsonobjectresult
							.getJSONObject("resultMap");
					JSONArray courseNotifList = resultMap
							.getJSONArray("CourseNotifAndOwner");
					for (int i = 0; i < courseNotifList.length(); i++) {
						JSONObject courseNotif = new JSONObject();
						courseNotif = courseNotifList.getJSONObject(i);

						// 将JsonObject存入本地数据库
						CourseNotifBean courseNotifBean = new CourseNotifBean();
						courseNotifBean.fillAttributeByJson(courseNotif);
						courseNotifDao.insertOrUpdate(courseNotifBean);

					}

				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 发送notifId从网上下拉通知具体内容和发布人的具体信息json
	 */
	public void downContentLoadData(String notifId) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("notifId", notifId));
		HttpPostTask task = new HttpPostTask(getActivity(),
				NotifUrl.GET_COURSE_NOTIF_AND_OWNER_BY_NOTIF_ID, params);
		task.setTaskListener(new OnTaskProcessListener() {
			@Override
			public void prepare() {
			}

			@Override
			public void completed(String result) {
				if (StringUtils.isEmptyOrStringNull(result)) {
					getDataFromDatabase();
				} else {
					Log.i("", "具体" + result);
					// 有网络登陆时
					analytical(result);
					getDataFromDatabase();
				}
				mAdapter.notifyDataSetChanged();
				ScreenSendUtils.sendWithDely(root);

			}

		});
		task.execute();
	}
/**
 * handsome
 * @param position
 */
	// 传递通知到的详细参数
	private void setBundle(int position) {
		CourseNotifDao courseNotifDao = new CourseNotifDao(getActivity(),
				getCourseUserId);
		List<CourseNotifBean> courseNotif = courseNotifDao
				.getNotifByCourseId(getCourseId);
		String userType = courseNotif.get(position).getUserBean().getType();
		String title = courseNotif.get(position).getTitle();
		String time = courseNotif.get(position).getCreateTime();
		String context = courseNotif.get(position).getContent();
		String name = courseNotif.get(position).getUserBean().getName();
		String image = courseNotif.get(position).getUserBean().getImageUrl();
		// String courseNotifId = courseNotif.get(position).getId();

		Bundle bundle = new Bundle();
		bundle.putString("userType", userType);
		bundle.putString("time", time);
		bundle.putString("context", context);
		bundle.putString("image", image);
		bundle.putString("name", name);
		bundle.putString("title", title);
		notifDetailFragment.setArguments(bundle);
	}

    @Override
    public void onResume() {
        super.onResume();
        ScreenSendUtils.sendWithDely(root);
    }
}
